'''
Provides custom-defined handlers for each type
of rcs repository supported in config.
'''

# Isolate parts of the url
from urlparse import urlparse
# Check if repo already cloned
import os.path

class RepoHandler:

  #----------------------------------
  # Update code below and add handler
  # at bottom for new repo host
  #----------------------------------
  handledRepos = ['github.com', 'bitbucket.org', 'googlecode.com']
  def __init__(self, dump):
    self.dump = dump.rstrip('/') + '/'
    self.handlers = {
      'github.com':      RepoHandler.githubHandler,
      'bitbucket.org':   RepoHandler.bitbucketHandler,
      'googlecode.com':  RepoHandler.googlecodeHandler
    }

  def supports(self, repos):
    for repo in repos:
      if repo not in RepoHandler.handledRepos:
        return False
    return True

  def getCommand(self, link):
    for repo in RepoHandler.handledRepos:
      if repo in link:
        return self.handlers[repo](link.rstrip('/'), self.dump)
    raise Exception, 'Unhandled link: ' + link

  #------------------------------
  # Custom defined handlers below
  #------------------------------
  
  @staticmethod
  def githubHandler(link, dump):
    projName = link.split('/')[-1]
    # Already cloned, just update
    if os.path.isdir(dump+projName):
      return 'cd ' + dump+projName + '; git pull'
    return 'git clone ' + link + '.git'

  @staticmethod
  def bitbucketHandler(link, dump):
    projName = link.split('/')[-1]
    if os.path.isdir(dump+projName):
      return 'cd ' + dump+projName + '; hg pull'
    return 'hg clone ' + link

  @staticmethod
  def googlecodeHandler(link, dump):
    scheme = urlparse(link).scheme
    projName = urlparse(link).netloc.split('.')[0]
    if link.endswith('hg'):
      if os.path.isdir(dump+projName):
        return 'cd ' + dump+projName + '; hg pull'
      return 'hg clone https://' + link.replace(scheme+'://', '') + '/ ' + projName
    elif link.endswith('svn'):
      if os.path.isdir(dump+projName):
        return 'cd ' + dump+projName + '; svn update'
      return 'svn checkout http://' + link.replace(scheme+'://', '') + '/trunk/ ' + projName
      
    return '- Failed handling ' + link

